package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserIncomeConstant;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.LotteryMapper;
import com.alipay.rebate.shop.dao.mapper.LotteryTimesRecordMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.helper.UserHelper;
import com.alipay.rebate.shop.model.Lottery;
import com.alipay.rebate.shop.model.LotteryTimesRecord;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.pojo.user.customer.PlusOrReduceVirMoneyReq;
import com.alipay.rebate.shop.service.customer.CustomerLotteryTimesRecordService;
import java.util.Date;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by CodeGenerator on 2019/10/22.
 */
@Service
@Transactional
public class LotteryTimesRecordServiceImpl extends AbstractService<LotteryTimesRecord> implements
    CustomerLotteryTimesRecordService {

    private Logger logger = LoggerFactory.getLogger(LotteryTimesRecordServiceImpl.class);
    @Resource
    private LotteryTimesRecordMapper lotteryTimesRecordMapper;
    @Resource
    private LotteryMapper lotteryMapper;
    @Resource
    private UserHelper userHelper;
    @Resource
    private UserMapper userMapper;

    @Override
    public Integer selectCurdayTimes(Long userId) {
        LotteryTimesRecord lotteryTimesRecord = lotteryTimesRecordMapper
            .selectCurDayTimesRecordByUserId(userId);
        if(lotteryTimesRecord == null){
            return 0;
        }
        return lotteryTimesRecord.getTimes();
    }

    @Override
    public Integer addOrUpdateCurDayTimes(Long userId, PlusOrReduceVirMoneyReq req) {

        // 抽奖配置
        Lottery lottery = lotteryMapper.selectCurrentUseLottery();

        //供测试类使用
//        Lottery lottery = lotteryMapper.selectLotteryById(1);

        logger.debug("maxTime, freeTime, consumeJf is : {}",
            lottery.getMaxTime(),lottery.getFreeTime(),lottery.getConsumeJf());
        // 当前抽奖次数
        LotteryTimesRecord lotteryTimesRecord = lotteryTimesRecordMapper
            .selectCurDayTimesRecordByUserId(userId);
        logger.debug("LotteryTimesRecord is : {}",lotteryTimesRecord);
        if (lotteryTimesRecord != null){
            // 如果已经到底抽奖次数上线
            checkIfReachMaxTimes(lottery,lotteryTimesRecord);
            // 如果没有超过免费抽奖次数
            if (lotteryTimesRecord.getTimes() < lottery.getFreeTime()){
                logger.debug("not reach free time");
                dealWhenNotReachFreeTime(userId,req);
            } else { // 超过免费次数扣除相应积分
                logger.debug("reach free time");
                dealWhenReachFreeTime(userId,req,lottery);
            }
            return lotteryTimesRecord.getTimes() + 1;
        }
        if(lottery.getMaxTime() <=0){
            throw new BusinessException("抽奖次数已达上限", StatusCode.Lottery_TIMES_REACHED);
        }
        if(lottery.getFreeTime() <=0){ // 如果免费次数小于0
            checkAndReduceUserIntegral(userId,lottery);
        }
        // 第一次抽奖
        firstTimeToLottery(userId,req);
        return 1;
    }

    private void firstTimeToLottery(Long userId,PlusOrReduceVirMoneyReq req){
        LotteryTimesRecord nRecord = new LotteryTimesRecord();
        nRecord.setTimes(1);
        nRecord.setUserId(userId);
        nRecord.setCreateDate(new Date());
        nRecord.setCreateTime(new Date());
        lotteryTimesRecordMapper.insertSelective(nRecord);
        // 添加用户收益
        if (req != null && req.isFlag()){
            userHelper.pluUserVirtualMoneyAndUserIncomeByType(req,userId);
        }
    }

    private void checkIfReachMaxTimes(Lottery lottery, LotteryTimesRecord lotteryTimesRecord){
        if(lottery.getMaxTime() <=0){
            throw new BusinessException("抽奖次数已达上限", StatusCode.Lottery_TIMES_REACHED);
        }
        // 如果已经到底抽奖次数上线
        if(lottery.getMaxTime()<=lotteryTimesRecord.getTimes()){
            throw new BusinessException("抽奖次数已达上限", StatusCode.Lottery_TIMES_REACHED);
        }
    }

    private void dealWhenNotReachFreeTime(Long userId,PlusOrReduceVirMoneyReq req){
        lotteryTimesRecordMapper.plusCurdayLotteryTimes(userId);
        if (req != null && req.isFlag()){
            userHelper.pluUserVirtualMoneyAndUserIncomeByType(req,userId);
        }
    }

    private void dealWhenReachFreeTime(Long userId,PlusOrReduceVirMoneyReq req,Lottery lottery){

        checkAndReduceUserIntegral(userId,lottery);
        lotteryTimesRecordMapper.plusCurdayLotteryTimes(userId);
        // 添加用户奖励
        if (req != null && req.isFlag()){
            userHelper.pluUserVirtualMoneyAndUserIncomeByType(req,userId);
        }

    }

    private void checkAndReduceUserIntegral(Long userId,Lottery lottery){
        if(lottery.getConsumeJf() <=0){// 如果消耗积分设置小于0, 直接返回
            return;
        }
        User user = userMapper.selectById(userId);
        logger.debug("user is : {}",user);
        logger.debug("lottery is : {}",lottery);
        if(user.getUserIntgeral() < lottery.getConsumeJf()){
            throw new BusinessException("积分不足", StatusCode.Lottery_TIMES_REACHED);
        }
        // 扣除用户积分
        PlusOrReduceVirMoneyReq nReq = new PlusOrReduceVirMoneyReq();
        nReq.setAwardType(UserIncomeConstant.IT_AWARD_TYPE);
        long num = Long.valueOf(lottery.getConsumeJf());
        nReq.setNum(-num);
        nReq.setType(UserIncomeConstant.LOTTERY_AWAED_TYPE);
        userHelper.pluUserVirtualMoneyAndUserIncomeByType(nReq,userId);
    }

}
